package com.mjgy.utils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonValueProcessor;
import net.sf.json.util.CycleDetectionStrategy;
import net.sf.json.util.PropertyFilter;

/**
* @Description: JSON工具类
* @author LGC
* @date 2018年9月12日
* @version V1.0
*/
@SuppressWarnings("unchecked")
public class JSONUtils {
	
	private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
	private static JsonConfig getJsonConfig(String[] excludes) {
		PropertyFilter filter = new PropertyFilter() {

			@Override
			public boolean apply(Object obj, String fieldName, Object fieldValue) {
				// 过滤List空值
				if(fieldValue instanceof List) {
					List<Object> list = (List<Object>) fieldValue;
					if(list.size() == 0) {
						return true;
					}
				}
				// 过滤空字段
				return fieldValue == null || "".equals(fieldValue);
			}
			
		};
		
		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.setExcludes(excludes);
		jsonConfig.setJsonPropertyFilter(filter);
		jsonConfig.registerJsonValueProcessor(Date.class, new DateJsonValueProcessor(sdf));
//		jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
		return jsonConfig;
	}
	
	/**
	 * 对象转JSON对象，增加排除字段
	 * 
	 * @param obj
	 * @param excludes
	 * @return
	 */
	public static JSONObject fromObject(Object obj, String[] excludes) {
		JsonConfig jsonConfig = getJsonConfig(excludes);
		return JSONObject.fromObject(obj, jsonConfig);
	}
	
	/**
	 * 数组转JSON数组，增加排除字段
	 * 
	 * @param objs
	 * @param excludes
	 * @return
	 */
	public static JSONArray fromArray(List<Object> objs, String[] excludes) {
		JsonConfig jsonConfig = getJsonConfig(excludes);
		JSONArray ja = new JSONArray();
		for(Object obj : objs) {
			JSONObject jo = JSONObject.fromObject(obj, jsonConfig);
			ja.add(jo);
		}
		return ja;
	}
	
	/**
	 * 时间转换
	 * 
	 * @author LGC
	 *
	 */
	private static class DateJsonValueProcessor implements JsonValueProcessor {

		private SimpleDateFormat sdf;
		
		public DateJsonValueProcessor(SimpleDateFormat sdf) {
			this.sdf = sdf;
		}
		
		@Override
		public Object processArrayValue(Object obj, JsonConfig config) {
			return sdf.format(obj);
		}

		@Override
		public Object processObjectValue(String str, Object obj, JsonConfig config) {
			return sdf.format(obj);
		}
		
	}
}
